package com.chinaunicom.emergency.test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chinaunicom.emergency.util.HttpClient;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


/**
 * @Author liliang
 * @Date 2020/7/28 15:46
 * @Version 1.0
 */
public class DataCenterRest {
    private static String privateKeyString = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCK+MBzAMbhkfbahbQvuZzP4nrU8k9y6xe7mkTp1FsQ7GX4PcohERJF3V/29dZgo0VmaQcVvnqDsYSJEm55LmenbVWLS1EqbWHA7xPhqsa+wLNL/5IrUHPvO3/kajztxzH0ysg4d63HDAw7gNOLay+3pV9+4a+O42D4U0PB/Z6yJAnZ7xznsALih8+IXDmlfP3uF2Tc5bcp73BeIzE2YONcPZcKXq7rEPbAc8fTzOiO42SnD9m+rOMGEdE0eB+C+WsXnrkI/Rn6VmErjx/Tf+Gi5d25Z3sf4/bWkb9917xKqEOdkH17+QqrPuDCV3qMB1ScFE4EWA/maahGReNQtm2fAgMBAAECggEAT8TtIpYFkqDoIxKwFNzkB+emPelAdWRAYSzx9Y4xH4uyFEXTahuUc4nYdbcy8JGHWnta175YMJOK0etEgkaCtPXrLmNzGXljrQ0OSnBuWDvgLvVp/3bUtTNf+8qHYqz+HdbwComXtDNUKiuOQe6qmy1PnVMKJGib1q5krEtZ9kIh6wS/nTR3vWfQguinrHmTzPUfLpjrtK+pp6E3+l7BIjkVbbP9GcyoJHl8/qgghXCbhgz5yzjDCfLe76hwM/yKfD9JZ5Y9LCTe+JUNl7lZBRnLS/WNwRC9LCaNd8QxOTDWgh+FsejvtR0IJHfbJ2ZmdMF0JWa7hm5T9+BBoW6R4QKBgQDek/FhD8lYwDpPllFUU9nttqfJJcN6yw3bG21v7XbTlC+k7hxKy2900jQlahm1FiQl165U/m6iDb/57A6UXIQC9kfawTyHfCyycXT/L7YfUHToog7s3HWZ/A6np3s1mWNcYQfjdxPtqcLOnGgkLCDrsEAzIB32bCRWCuYzEmmGaQKBgQCf1uzFUQwurIi4O822bEqbVukpqUcM2G1jSaG8lBEIKqJGgPep+V+Xnjwj4AIswEM4SUJ135IetSAPsd7oa43ZF5GLqJfpmPKwQUuITkRUiWGdmsNfd12NV3xRU3G8+bCzVUOAmTtItXOKy4wsgAmYD2S15U9P3vLdtgQ6rY0ixwKBgE871ze4SPMBK0DdwAIG/5Nx7HTcrqPt2Pbg4qpvnFdhbzyFTykJFpo9ojaXeKNQSHn4N6UmFfg2cNrlP6Ns88miJp4nIAcTG05CuWWGdIzdNWEDH9EOAgdZBVaFdoT0H7zpBcfhwgRe5GxsnV4TH30HdzM8Aa6RfLXsl1oi+dHRAoGAUhn0rnmt9z96Tp+xT7WaMOZYh6TCsQ9uSKSmphWsFfTIO8y86hsEhf2qSIckttXe8Ud4EtHO3WUN3eHwbJPqXYtkoEbuGPgOGIjBgncpU/7pHCpFloDaleJNIfzpnDbpE4SFUsXilLtXaQCatLTjuK6XfXMW5SDQwR9gVr+UkjsCgYEAidsmsVplLpxzp7F6k17paEiw3vn8yghDI7JX8jmRYp4gWWbX+wfBr0OtDfB5X6Y39reuvdA2XmUs9/3cZ1l5BN/O4Ci1E/Q0VSHn+H6/z+MNJ5LGKw3ebErU9FingPRtb2Pv4YjpkQgIbexenIbu5BzT/kVoXoFDsXb0g3VUJ+0=";
    private static String userId = "e382532484cd00210b1de117f294e6e2";

    public static void main(String[] args)
            throws Exception {
        String rsaKey = getTokenPostData();

        //获取token
        String token = getToken(rsaKey);
        System.out.println(token);
        //获取用户表数据
        List tableUserList= getTableUserData(token);
        System.out.println(tableUserList);







    }

    private static String getToken(String body) throws Exception{
        String token = "";
        Map<String, String> headPara = new HashMap<>();
        //http://域名/x-authentication-service/v1/tokens
        String url = "http://192.168.24.164:30003/x-authentication-service/v1/tokens";
        JSONObject tokenJson = JSONObject.parseObject(HttpClient.postHtmlData(url, body, headPara));
        //code	int	返回码（0：成功，1失败）201	Created  400	Bad Request  500	Internal Server Error
        //message	string	返回消息
        //data	string	token字符串
        System.out.println(tokenJson);
        if (201 == tokenJson.getInteger("code")) {
            return tokenJson.getString("data");
        }
        return token;
    }


    private static List getTableUserData(String token) throws Exception{

        List list = Lists.newArrayList();
        Map<String, String> headPara = new HashMap<>();
        //header参数
            //x-token	string	必填	上面获取的token
        headPara.put("x-token",token);
        headPara.put("x-token",token);

        Map<String, String> bodyPara = new HashMap<>();
        //body请求参数
            // columns	string	可选	需要输出的字段名称（多个则用逗号分隔），例如： id,username,mobile
            //	filter	string	可选	过滤条件（where后的内容），如果需要筛选分区，将筛选条件加上分区条件即可。例如：id>4 （url编码后为：id%3E4）注：过滤条件不能使用limit，limit功能需通过pageCount与pageNumber参数实现
            //	pageCount	long	可选	每页显示的条数（最大为500，默认500，超过500按500计算）
            //	pageNumber	long	可选	当前的页数（从1开始,默认为1）
//        bodyPara.put("columns","id,xm");

        //http://域名/x-data-resource-service/v1/resources/data-provider/{table_name}
        String url = "http://192.168.24.164:30003/x-data-resource-service/v1/resources/data-provider/user_a";
        String result = HttpClient.getHtmlData(url, bodyPara, headPara);
        //返回:字符串，每行是一条数据，JSON格式。
        //{"id":"5","name":"username5"}
        //{"id":"6","name":"username6"}
        //{"id":"7","name":"username7"}
        //{"id":"8","name":"username8"}
        String[] args = result.split("\n");
        for(String arg : args){
            if(StringUtils.isNotBlank(arg)){
                list.add(JSONObject.parseObject(arg).toJavaObject(TestUser.class));
            }
        }
        return list;
    }


    /**
     * 生成通讯加密串
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    private static String getTokenPostData()
            throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {
        // 根据用户ID和当前时间，拼接成待加密的内容
        String secretBody = userId + "#" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        // 使用RSA的私钥对其进行加密
        KeyFactory factory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
                Base64.getDecoder().decode(privateKeyString));
        PrivateKey privateKey = factory.generatePrivate(privateKeySpec);
        Cipher encryptCipher = Cipher.getInstance("RSA");
        encryptCipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] finalData = encryptCipher.doFinal(secretBody.getBytes());
        String finalDataString = new String(Base64.getEncoder().encode(finalData));

        // 最终用于获取token的字符串
        return userId + "#" + finalDataString;
    }


}
